package com.wchat.server.codec;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.wchat.bean.model.MsgPayload;
import com.wchat.bean.model.body.AckBody;
import com.wchat.bean.model.body.ChatMsgBody;
import com.wchat.bean.model.body.EventBody;
import com.wchat.bean.model.enums.HeaderTypeEm;
import com.wchat.bean.model.enums.TypeEm;
import com.wchat.server.ClientManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : willian fu
 * @date : 2020/5/30
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class WsMessageCodec extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Autowired
    private ClientManager clientManager;

    @Override
    protected void channelRead0(ChannelHandlerContext channel, TextWebSocketFrame msg) throws Exception {
        MsgPayload payload = JSON.parseObject(msg.text(), MsgPayload.class);
        JSONObject body = (JSONObject) payload.getBody();
        if (HeaderTypeEm.CHAT.equals(payload.getHeader()) && TypeEm.CHAT_MSG.equals(payload.getType())){
            payload.setBody(body.toJavaObject(ChatMsgBody.class));
        }else if (HeaderTypeEm.EVENT.equals(payload.getHeader())){
            payload.setBody(body.toJavaObject(EventBody.class));
        }else if (HeaderTypeEm.ACK.equals(payload.getHeader())){
            payload.setBody(body.toJavaObject(AckBody.class));
        }
        channel.fireChannelRead(payload);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("Websocket设备[{}]数据包不合法",ctx.channel().remoteAddress().toString(), cause);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //有设备连接上来，应该加入鉴权计时队列
       // clientManager.online(clientManager.getSession(ctx.channel()).getUserId(), ctx.channel());
        log.info("Websocket设备[{}]连接上了", ctx.channel().remoteAddress().toString());
    }

}
